<?php
/**
 *
 * Author: TheSmile
 * Date: 2024/11/4 17:11
 * Email: <594652523@qq.com>
 */

namespace App\Exports;

use App\Models\CourseDuty;
use App\Models\CourseOrder;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class UserEnroll extends ExcelExporter implements WithMapping, WithColumnWidths, WithStyles
{
    protected $fileName = '学员库.xlsx';

    protected $columns = [
        'id'       => '学员ID',
        'nickname' => '昵称',
        'mobile'   => '电话',
        'score'    => '积分',
        'intro'    => '已报课程',//随便找个模型不用的字段
        'avatar'   => '已上课程'//随便找个模型不用的字段
    ];

    public function columnWidths(): array
    {
        return ['B' => 20, 'C' => 20, 'E' => 50, 'F' => 50];
    }

    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle('E')->getAlignment()->setWrapText(true); // 设置具体单元格的换行
        $sheet->getStyle('F')->getAlignment()->setWrapText(true); // 设置具体单元格的换行
    }

    public function map($user): array
    {

        return [
            $user->id,
            $user->nickname,
            $user->mobile,
            $user->score,
            self::getCourseOrder($user),
            self::getDutyCourse($user)
        ];
    }

    protected static function getCourseOrder($user)
    {
        $orders = CourseOrder::where('user_id', $user->id)->where('status', '!=', -1)->where('status', '!=', 1)->where('status', '!=', 4)
            ->with("courseInfo")
            ->get(['course_id', 'user_id', 'created_at'])->toArray();
        $str    = '';
        if (!empty($orders)) {
            foreach ($orders as $item) {
                $str .= $item['created_at'] . $item['course_info']['name'] . PHP_EOL;
            }
            $str = substr($str, 0, -1);
        }
        return $str;
    }

    protected static function getDutyCourse($user)
    {
        $orders = CourseDuty::where('user_id', $user->id)
            ->with("courseInfo")
            ->get(['course_id', 'user_id', 'created_at'])->toArray();
        $str    = '';
        if (!empty($orders)) {
            foreach ($orders as $item) {
                $str .= $item['created_at'] . $item['course_info']['name'] . PHP_EOL;
            }
            $str = substr($str, 0, -1);
        }
        return $str;
    }
}
